use strict;
use warnings;
use Purple;

our %PLUGIN_INFO = (
    perl_api_version => 2,
    name => "Fortune Plugin",
    version => "0.1",
    summary => "Fortune plugin.",
    description => "Set fortune output as status when plugin load.",
    author => "Zhao Xiaohong <mrluanma\@gmail.com",
    url => "http://pidgin.im",
    load => "plugin_load",
    unload => "plugin_unload",
    prefs_info => "prefs_info_cb"
    );

sub plugin_init {
    return %PLUGIN_INFO;
}

sub fortune_cb {
    my ($plugin, $fortune) = @_;

    my $status_message = `$fortune`;
    $status_message =~ s/\\[32m|\\[33m|\\[m//g;
    my $saved_status = Purple::SavedStatus::get_current();
    my $prev_status = $saved_status->get_message();

    Purple::Debug::info("Fortune Plugin", "Updating status message with ".$status_message."\n");
    $saved_status->set_message($status_message);
    $saved_status->activate();
}

sub timeout_cb {
    my $plugin = shift;
    my $timeout = 0+Purple::Prefs::get_string("/plugins/core/fortune/timeout");
    if($timeout eq 0) {
        Purple::Debug::info("Fortune Plugin", "Could not parse timeout field. Using 120 seconds default.\n");
        $timeout = 120;
    }
    my $fortune = Purple::Prefs::get_string("/plugins/core/fortune/program");

    fortune_cb($plugin, $fortune);

    # Reschedule timeout
    Purple::Debug::info("Fortune Plugin", "Rescheduling timer.\n");
    Purple::timeout_add($plugin, $timeout, \&timeout_cb, $plugin);
    Purple::Debug::info("Fortune Plugin", "New timer set for " . $timeout . " seconds.\n");
}

sub plugin_load {
    my $plugin = shift;
    Purple::Debug::info("Fortune Plugin", "plugin_load() - Fortune plugin Loaded.\n");

    Purple::Prefs::add_none("/plugins/core/fortune");
    Purple::Prefs::add_string("/plugins/core/fortune/program", "/usr/games/fortune");
    Purple::Prefs::add_string("/plugins/core/fortune/timeout", "1200");

    # Schedule a timeout for 1 second from now
    Purple::timeout_add($plugin, 10, \&timeout_cb, $plugin);
}

sub plugin_unload {
    my $plugin = shift;
    Purple::Debug::info("Fortune Plugin", "plugin_unload() - Fortune plugin Unloaded.\n");
}

sub prefs_info_cb {
    # The first step is to initialize the Purple::Pref::Frame that will be returned
    my $frame = Purple::PluginPref::Frame->new();

    my $label = Purple::PluginPref->new_with_label("Fortune status");
    $frame->add($label);

    # Create a text box.  The default value will be "/usr/games/fortune"
    my $ppref = Purple::PluginPref->new_with_name_and_label(
        "/plugins/core/fortune/program", "Fortune program");
    $ppref->set_type(2);
    $ppref->set_max_length(120);
    $frame->add($ppref);

    # Adding the timeout box
    my $tpref = Purple::PluginPref->new_with_name_and_label(
        "/plugins/core/fortune/timeout", "Timeout Period");
    $tpref->set_type(2);
    $tpref->set_max_length(3);
    $frame->add($tpref);

    return $frame;
}
